package jmind.core.support.servlet;

import jmind.base.util.AppEnvironment;
import jmind.base.util.DataUtil;
import jmind.core.aspect.MethodMonitorAspect;
import jmind.core.cache.support.StatsCounterHtmlTemplate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: xieweibo
 * @Date: 2018/5/24
 * 针对spring boot 使用@ServletComponentScan   这个注解既可以扫描 @WebServlet 还可以扫描@WebFilter
 * @ServletComponentScan({"jmind.pigg.plugin.stats","jmind.core.support.servlet"})
 */
@WebServlet(name="method-stat",urlPatterns="/method-stat")
public class MethodStatServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type", "text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        if("clear".equalsIgnoreCase(req.getParameter("op"))){
            MethodMonitorAspect.STATS_COUNTER_CACHE.clear();
        }

        try {
            out.println(StatsCounterHtmlTemplate.render(MethodMonitorAspect.STATS_COUNTER_CACHE.stat(), DataUtil.toInt(AppEnvironment.getProperty("methodMonitor.slow","200"))));
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            out.println(e.getMessage());
            out.flush();
        }
    }
}
